﻿using System;
using System.Reflection;
using CompactMapper.Orm.Contracts;
using CompactMapper.Orm.Extensions;
using CompactMapper.Orm.Annotations;

namespace CompactMapper.Orm.UnitOfWork.Mappings.Meta.PropertyInfos.Columns
{
    internal interface IPrimaryKeyColumn : IColumn
    {
    }

    internal class PrimaryKeyColumn : Column, IPrimaryKeyColumn
    {
        private readonly String _sqlType;
        private readonly String _typeName;
        public PrimaryKeyColumn(PropertyInfoPersistenceAttributePair pair)
            : base(pair.PropertyInfo)
        {
            var primaryKeyAttribute = (PrimaryKeyAttribute)pair.PersistenceAttribute;
            _sqlType = primaryKeyAttribute.SqlType.ToSqlColumn();
            _typeName = primaryKeyAttribute.KeyType.Name;
        }


        public override string SqlType
        {
            get { return _sqlType; }
        }

        protected override object ToSqLiteObjectNonEnumeration(object target)
        {
            return ((IKey)GetValue(target)).Value;
        }

        protected override object FromSqLiteObjectNonEnumeration(object source)
        {
            var key = AbstractKeyFactory.For(_typeName).Hidrate(source);
            return key;
        }
    }
}